package com.yang.qqservice.service;

import com.yang.common.Message;
import com.yang.common.MessageType;
import com.yang.utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Date;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 服务器推送新闻业务类
 * @Author: YANG QIANG
 * @Time: 2022-12-21 22:15
 */
public class SendNewsToAllService implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("请输入需要推送的新闻/消息, 输入exit退出发送新闻服务");
            String news = Utility.readString(100);
            if ("exit".equals(news)){
                break;
            }

            // 封装为群发消息
            Message message = new Message();
            message.setContent(news);
            message.setSender("服务器");
            message.setSendTime(new Date().toString());
            message.setMessageType(MessageType.MESSAGE_C0MM_MES_TO_ALL);

            // 遍历所有在线用户的线程, 然后发送
            ConcurrentHashMap<String, ServerConnectClientThread> hm = ManageClientThread.getHm();
            Iterator<String> iterator = hm.keySet().iterator();
            while (iterator.hasNext()){
                ServerConnectClientThread serverConnectClientThread = hm.get(iterator.next());
                Socket socket = serverConnectClientThread.getSocket();
                // 发送给用户
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
